# FLOYD CYCLE DETECTION ALGORITHM
----------------------------------

        A        B
    1 -> 2 -> 3 ---> 4
              ^      | C
              '- 5 <-'


-> Two pointer approach to detect a cycle in a LinkedList
-> Time Complexity: O(n)
-> Space Complexity: O(1)

-> create a "fast" pointer and a "slow" pointer
-> move the two pointers at different speeds through the LinkedList in search of fast.next pointing to NULL
-> if the two pointers collide at nay given time, Cycle should be marked as detected, else mark is not-detected

Mathematical Proof:
-------------------

//slow moves m turns, and fast moves n turns in the loop before meeting at junction -> n>m
=> distance travelled by slow * 2 = distance travelled by fast
=> (A + m(B+C)) * 2 = A + n(B+C)
=> A + B = (n-m)(B+C)
=> A + B = K (B+C)      //A+B is an integral multiple of B + C

Detect Cycle:
-------------

    public static boolean FloydCycleDetection(Node head){
        Node slow = head;
        Node fast = head;

        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }

Detect the Junction:
--------------------
    public static Node DetectJunction(Node head){
        Node meet = FloydCycleDetection(head);      //return the meeting point
        Node start = head;

        while(start!=meet){
            start = start.next;
            meet = meet.next;
        }

        return start;
    }

Remove Loop from LL:
--------------------
public static void removeLoop(Node head){
        // remove the loop without losing any nodes
        Node slow = head;
        Node fast = head;
        boolean loop = false;

        //at the end of this loop fast and slow will be at "meet" (not necessarily "junction")
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                loop = true;
                break;
            }
        }

        if(loop){
            slow=head;
            // loop to send slow and fast to junction
            while(slow!=fast){
                slow = slow.next;
                fast = fast.next;
            }

            // loop to move fast to the node to point just before junction,
            // so that we make its next -> null
            while(fast.next!=slow){
                fast = fast.next;
            }
            fast.next=null;
        }
    }